package com.hotelManagerSystem.shiro;

import com.hotelManagerSystem.model.User;
import com.hotelManagerSystem.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author treasy
 * @description 用于客户登录和授权
 */
public class ShiroRealmCustomer extends AuthorizingRealm {
    @Autowired
    IUserService iUserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用CustomerRealm认证");
        //1.通过token获取用户名
        String username = (String) authenticationToken.getPrincipal();
        System.out.println(username);
        //2.查询customer的user数据库获取用户信息
        User user = iUserService.queryByUsername(username);
        System.out.println(user);
        //3.shiro判断用户
        if (user==null){
            return null;//shiro底层抛出UnknownAccountException异常
        }
        //4.判断密码
        ByteSource salt = ByteSource.Util.bytes(user.getSalt());//通过shiro自带工具将盐值转换为byte类型
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),salt,getName());
        return info;
    }
}
